package com.ashley.phonemsn

import android.Manifest
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.app.Activity
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.CallEnd
import androidx.compose.material.icons.filled.Dialpad
import androidx.compose.material.icons.filled.PersonSearch
import androidx.compose.material.icons.filled.VolumeUp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.ashley.phonemsn.ui.theme.PhoneMSNTheme
import java.text.SimpleDateFormat
import java.util.*

class CallFragment : Fragment() {
    private val CALL_PERMISSION_REQUEST_CODE = 1002
    private val PHONE_STATE_PERMISSION_REQUEST_CODE = 1003
    private val TAG = "CallFragment"

    // ViewModel
    private lateinit var viewModel: CallViewModel
    
    // 联系人选择回调
    private var onContactSelectedCallback: ((String) -> Unit)? = null

    // 注册权限请求
    private val requestCallPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            // 权限被授予，可以拨打电话
            viewModel.makePhoneCall(requireContext())
        } else {
            // 显示详细的权限说明
            showPermissionRationale("拨打电话", "此权限允许应用拨打电话。如果您拒绝此权限，将无法使用拨号功能。")
        }
    }
    
    // 注册多个权限请求
    private val requestMultiplePermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            // 所有权限都被授予
            viewModel.setupPhoneStateListener(requireContext())
        } else {
            // 显示权限说明
            showPermissionRationale("电话状态监听", "此权限允许应用监听来电状态。如果您拒绝此权限，将无法接听来电。")
        }
    }

    // 注册电话状态监听权限请求
    private val requestPhoneStatePermissionLauncher = registerForActivityResult(
    
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            // 权限被授予，设置电话状态监听
            viewModel.setupPhoneStateListener(requireContext())
        } else {
            android.util.Log.w(TAG, "电话状态监听权限被拒绝")
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 初始化ViewModel
        viewModel = ViewModelProvider(this)[CallViewModel::class.java]
        viewModel.initServices(requireContext())

        return ComposeView(requireContext()).apply {
            setContent {
                PhoneMSNTheme {
                    if (viewModel.isIncomingCall.value) {
                        // 来电界面
                        IncomingCallScreen(
                            phoneNumber = viewModel.incomingCallNumber.value,
                            onAnswerCall = { viewModel.answerIncomingCall(requireContext()) },
                            onRejectCall = { viewModel.rejectIncomingCall(requireContext()) }
                        )
                    } else if (viewModel.isInCall.value) {
                        // 通话中界面
                        InCallScreen(
                            phoneNumber = viewModel.phoneNumber.value,
                            startTime = viewModel.callStartTime,
                            duration = viewModel.callDuration.value,
                            onEndCall = { viewModel.endCall(requireContext()) },
                            onToggleSpeaker = { viewModel.toggleSpeaker(requireContext()) },
                            onShowDialpad = { viewModel.showDialpad(requireContext()) }
                        )
                    } else {
                        // 拨号界面
                        CallFragmentContent(this@CallFragment)
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkPhoneStatePermission()
    }

    override fun onPause() {
        super.onPause()
        viewModel.removePhoneStateListener()
    }

    // 检查电话状态权限
    private fun checkPhoneStatePermission() {
        if (viewModel.checkPhoneStatePermission(requireContext())) {
            // 已有权限，设置电话状态监听
            viewModel.setupPhoneStateListener(requireContext())
        } else {
            // 请求权限
            requestPhoneStatePermissionLauncher.launch(Manifest.permission.READ_PHONE_STATE)
        }
    }

    // 请求拨打电话权限
    fun requestCallPermission() {
        // 检查权限
        when {
            ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.CALL_PHONE
            ) == android.content.pm.PackageManager.PERMISSION_GRANTED -> {
                // 已有权限，直接拨打电话
                viewModel.makePhoneCall(requireContext())
            }
            else -> {
                // 请求权限
                requestCallPermissionLauncher.launch(Manifest.permission.CALL_PHONE)
            }
        }
    }

    // 为Composable函数提供访问ViewModel的公共方法
    fun getViewModel(): CallViewModel {
        return viewModel
    }
    
    // 更新电话号码
    fun updatePhoneNumber(newNumber: String) {
        viewModel.updatePhoneNumber(newNumber)
    }

    // 设置联系人选择回调
    fun setOnContactSelectedCallback(callback: (String) -> Unit) {
        this.onContactSelectedCallback = callback
    }

    // 处理选择的联系人
    fun onContactSelected(phoneNumber: String, contactName: String? = null) {
        if (onContactSelectedCallback != null) {
            onContactSelectedCallback!!(phoneNumber)
        } else {
            // 如果没有设置回调，则更新ViewModel中的电话号码和联系人名称
            viewModel.updatePhoneNumber(phoneNumber, contactName)
        }
    }
    
    // 显示权限说明对话框
    private fun showPermissionRationale(title: String, message: String) {
        android.util.Log.i(TAG, "$title 需要权限: $message")
    }
    
    // 添加启动ContactActivity的结果监听器
    // 启动联系人选择Activity的公共方法
    fun launchContactActivity() {
        val intent = Intent(requireContext(), ContactActivity::class.java)
        startContactActivityForResult.launch(intent)
    }
    
    // 联系人选择ActivityResultLauncher
    private lateinit var startContactActivityForResult: ActivityResultLauncher<Intent>
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 注册ActivityResultLauncher
        startContactActivityForResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val phoneNumber = result.data?.getStringExtra(ContactActivity.EXTRA_PHONE_NUMBER)
                val contactName = result.data?.getStringExtra(ContactActivity.EXTRA_CONTACT_NAME)
                phoneNumber?.let {
                    onContactSelected(it, contactName)
                }
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 移除电话状态监听器
        viewModel.removePhoneStateListener()
    }

}

@Composable
fun CallFragmentContent(
    fragment: Fragment
) {
    // 从Fragment获取ViewModel
    val callFragment = fragment as CallFragment
    val viewModel = callFragment.getViewModel()
    
    // 直接获取phoneNumber状态
    val phoneNumber: String by viewModel.phoneNumber
    // 直接获取contactName状态
    val contactName: String by viewModel.contactName
    
    // 监听ViewModel中电话号码的变化，确保UI与ViewModel状态同步
    LaunchedEffect(viewModel.phoneNumber.value) {
        // 无需额外操作，phoneNumber已经是从ViewModel派生的状态
    }

    Column(modifier = Modifier.fillMaxSize()) {
        // 顶部标题栏
        Surface(
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "电话",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
                
                // 右上角通讯录按钮
                Button(
                    onClick = {
                        // 启动ContactActivity
                        (fragment as CallFragment).launchContactActivity()
                    },
                    shape = CircleShape,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color.White.copy(alpha = 0.2f)
                    )
                ) {
                    Icon(
                        imageVector = Icons.Filled.PersonSearch,
                        contentDescription = "通讯录",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }

        // 电话号码显示
        Text(
//            text = if (contactName.isNotEmpty()) contactName else (if (phoneNumber.isEmpty()) "请输入电话号码" else phoneNumber),
            text = phoneNumber.ifEmpty { "请输入电话号码" },
            fontSize = 32.sp,
            fontWeight = FontWeight.Medium,
            modifier = Modifier.padding(16.dp)
        )

        Spacer(modifier = Modifier.height(20.dp))

        // 数字键盘
        Column(modifier = Modifier.padding(16.dp)) {
            // 第一行: 1 2 3
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                NumberButton("1", "ABC") {
                    viewModel.updatePhoneNumber("${phoneNumber}1")
                }
                NumberButton("2", "DEF") {
                    viewModel.updatePhoneNumber("${phoneNumber}2")
                }
                NumberButton("3", "GHI") {
                    viewModel.updatePhoneNumber("${phoneNumber}3")
                }
            }

            // 第二行: 4 5 6
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                NumberButton("4", "JKL") {
                    viewModel.updatePhoneNumber("${phoneNumber}4")
                }
                NumberButton("5", "MNO") {
                    viewModel.updatePhoneNumber("${phoneNumber}5")
                }
                NumberButton("6", "PQRS") {
                    viewModel.updatePhoneNumber("${phoneNumber}6")
                }
            }

            // 第三行: 7 8 9
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                NumberButton("7", "TUV") {
                    viewModel.updatePhoneNumber("${phoneNumber}7")
                }
                NumberButton("8", "WXYZ") {
                    viewModel.updatePhoneNumber("${phoneNumber}8")
                }
                NumberButton("9", "") {
                    viewModel.updatePhoneNumber("${phoneNumber}9")
                }
            }

            // 第四行: * 0 #
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                NumberButton("*", "") {
                    viewModel.updatePhoneNumber("${phoneNumber}*")
                }
                NumberButton("0", "+") {
                    viewModel.updatePhoneNumber("${phoneNumber}0")
                }
                NumberButton("#", "") {
                    viewModel.updatePhoneNumber("${phoneNumber}#")
                }
            }
        }

        Spacer(modifier = Modifier.height(20.dp))

        // 操作按钮行
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            // 清除按钮
            Button(
                onClick = {
                    if (phoneNumber.isNotEmpty()) {
                        viewModel.updatePhoneNumber(phoneNumber.substring(0, phoneNumber.length - 1))
                    }
                },
                modifier = Modifier.size(70.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.secondary
                )
            ) {
                Text("删除", fontSize = 12.sp)
            }

            // 拨号按钮
            Button(
                onClick = {
                    fragment.requestCallPermission()
                },
                modifier = Modifier.size(70.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Icon(
                    imageVector = Icons.Filled.Call,
                    contentDescription = "拨号",
                    modifier = Modifier.size(28.dp)
                )
            }
            
            // 空占位，保持布局平衡
            Spacer(modifier = Modifier.size(70.dp))

            // 清除全部按钮
            Button(
                onClick = {
                    viewModel.updatePhoneNumber("")
                },
                modifier = Modifier.size(70.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.secondary
                )
            ) {
                Text("清除", fontSize = 12.sp)
            }
        }

        Spacer(modifier = Modifier.height(20.dp))
    }
}

@Composable
fun NumberButton(number: String, letters: String, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        modifier = Modifier
            .size(80.dp)
            .padding(4.dp),
        shape = CircleShape
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(
                text = number,
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold
            )
            if (letters.isNotEmpty()) {
                Text(
                    text = letters,
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
fun InCallScreen(
    phoneNumber: String,
    startTime: Long,
    duration: String,
    onEndCall: () -> Unit,
    onToggleSpeaker: () -> Unit,
    onShowDialpad: () -> Unit
) {
    val startTimeFormatted = remember {
        SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(startTime))
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        // 顶部信息
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 60.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "通话中",
                fontSize = 18.sp,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Text(
                text = phoneNumber,
                fontSize = 28.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Text(
                text = duration,
                fontSize = 16.sp,
                color = MaterialTheme.colorScheme.secondary,
                modifier = Modifier.padding(bottom = 4.dp)
            )

            Text(
                text = "开始时间: $startTimeFormatted",
                fontSize = 12.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        // 底部操作按钮
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 60.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 第一行操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 扬声器按钮
                IconButton(
                    onClick = onToggleSpeaker,
                    modifier = Modifier.size(60.dp)
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(
                            imageVector = Icons.Filled.VolumeUp,
                            contentDescription = "扬声器",
                            modifier = Modifier.size(30.dp)
                        )
                        Text("扬声器", fontSize = 12.sp)
                    }
                }

                // 拨号盘按钮
                IconButton(
                    onClick = onShowDialpad,
                    modifier = Modifier.size(60.dp)
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(
                            imageVector = Icons.Filled.Dialpad,
                            contentDescription = "拨号盘",
                            modifier = Modifier.size(30.dp)
                        )
                        Text("拨号盘", fontSize = 12.sp)
                    }
                }
            }

            Spacer(modifier = Modifier.height(40.dp))

            // 挂断按钮
            Button(
                onClick = onEndCall,
                modifier = Modifier
                    .size(80.dp)
                    .padding(16.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Icon(
                    imageVector = Icons.Filled.CallEnd,
                    contentDescription = "挂断",
                    modifier = Modifier.size(40.dp),
                    tint = MaterialTheme.colorScheme.onError
                )
            }
        }
    }
}

// 来电界面组件
@Composable
fun IncomingCallScreen(
    phoneNumber: String,
    onAnswerCall: () -> Unit,
    onRejectCall: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // 来电图标
        Icon(
            imageVector = Icons.Filled.Call,
            contentDescription = "来电",
            modifier = Modifier.size(120.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(32.dp))
        
        // 来电标题
        Text(
            text = "来电",
            fontSize = 28.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.onSurface
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 电话号码
        Text(
            text = phoneNumber,
            fontSize = 24.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Spacer(modifier = Modifier.height(48.dp))
        
        // 接听和拒绝按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            // 接听按钮
            Button(
                onClick = onAnswerCall,
                modifier = Modifier
                    .size(100.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                Icon(
                    imageVector = Icons.Filled.Call,
                    contentDescription = "接听",
                    modifier = Modifier.size(50.dp),
                    tint = MaterialTheme.colorScheme.onPrimary
                )
            }
            
            // 拒绝按钮
            Button(
                onClick = onRejectCall,
                modifier = Modifier
                    .size(100.dp),
                shape = CircleShape,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Icon(
                    imageVector = Icons.Filled.CallEnd,
                    contentDescription = "拒绝",
                    modifier = Modifier.size(50.dp),
                    tint = MaterialTheme.colorScheme.onError
                )
            }
        }
        
        Spacer(modifier = Modifier.height(32.dp))
        
        // 操作提示
        Text(
            text = "滑动接听或点击按钮操作",
            fontSize = 14.sp,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}